package com.hotelvip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hotelvip.common.exception.ServiceException;
import com.hotelvip.dao.LabelMapper;
import com.hotelvip.entity.Label;
import com.hotelvip.entity.UserLabel;
import com.hotelvip.service.LabelService;
import com.hotelvip.service.batch.UserLabelService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ypb
 * @date 2021-1-14 10:08:04
 * @Method updateById();
 * 修改用户的特殊情况
 */

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class LabelServiceImpl extends ServiceImpl<LabelMapper, Label> implements LabelService {


    @Autowired
    private UserLabelService userLabelService;

    @Autowired
    private LabelMapper labelMapper;

    /**
     * 通过用户id修改此用户的label (特殊情况)
     */
    @Override
    public void updateLabelById(Long userId, List<Label> labels) {
        //1.将所有的标签全部不重复的添加到label表中
        if (labels == null || labels.size()==0){
            return;
        }
        //批量插入 有重复的字段插入时会报错 所以不添加判断机制即使失败也不会提示
        boolean b = labelMapper.saveIgnoreExist(labels);
        //获取刚刚插入生成的id
        ArrayList<Integer> ids1 = new ArrayList<>();
        //对ids出去null值
        for (Label label : labels) {
            if (label.getId() != null) {
                ids1.add(label.getId());
            }
        }
        //2.修改时删除当前用户的中间表 重新添加
        UpdateWrapper<UserLabel> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(UserLabel::getUserId, userId);
        userLabelService.remove(wrapper);

        //3.添加中间表
        //获取到刚存存进去的id
        List<Integer> ids2 = labels.stream().map(Label::getId).collect(Collectors.toList());
        ids1.addAll(ids2);
        //去重
        List<Integer> ids = ids1.stream().distinct().collect(Collectors.toList());
        //添加实体对象 存入中间表
        ArrayList<UserLabel> userLabels = new ArrayList<>();
        for (Integer id : ids) {
            userLabels.add(new UserLabel().setId(null).setUserId(userId).setLabelId(id));
        }
        boolean b1 = userLabelService.saveBatch(userLabels);
        if (!b1) {
            throw new ServiceException("更新失败");
        }
    }

    @Override
    public List<Label> selectAllLabel() {
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(Label::getId);
        List<Label> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("未查询到标签,请添加!!!");
        }
        return list;
    }

    @Override
    public void deleteLabel(List<Integer> labelIds) {
        QueryWrapper<Label> wrapper = new QueryWrapper<>();

        wrapper.lambda().in(Label::getId,labelIds);

        List<Label> list = list(wrapper);
        List<Integer> collect = list.stream().map(Label::getId).collect(Collectors.toList());
        boolean b = remove(wrapper);
        if (!b) {
            throw new ServiceException("删除失败,请重试");
        }
        //同时需要删除用户绑定的标签
        //获取labelId 先判断id集合是否为空 避免空指针
        if (CollectionUtils.isNotEmpty(collect)) {
            UpdateWrapper<UserLabel> updateWrapper = new UpdateWrapper<>();

            updateWrapper.lambda().in(UserLabel::getLabelId, collect);
            //通过id查询用户是否使用者标签
            List<UserLabel> userLabelList = userLabelService.list(updateWrapper);
            if (CollectionUtils.isNotEmpty(userLabelList)) {
                boolean b1 = userLabelService.remove(updateWrapper);
                if (!b1) {
                    throw new ServiceException("删除时出现了意料之外的事情^_^");
                }
            }
        }
    }

    @Override
    public void insertLabels(List<String> labels) {


        //批量插入时数据库中没有的行会添加成功,存在的行会添加失败,说明已存在标签
        List<Label> labels1 = new ArrayList<>();
        if (CollectionUtils.isEmpty(labels)&&labels==null) {
           throw new ServiceException("添加失败,标签不能为空");
        }
        for (String label : labels) {
            labels1.add(new Label(null,label));
        }
        boolean b = labelMapper.saveIgnoreExist(labels1);

      /*  List<Label> labelList = new ArrayList<>();
        for (String label : labels) {
            labelList.add(new Label().setLabel(label));
        }
        //批量插入
        boolean b = labelMapper.saveIgnoreExist(labelList);
        System.out.println(b);*/
    }

    @Override
    public List<Label> selectLabelById(Long userId) {
        QueryWrapper<UserLabel> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserLabel::getUserId, userId);
        List<UserLabel> list = userLabelService.list(wrapper);
        List<Integer> labelIds = list.stream().map(UserLabel::getLabelId).collect(Collectors.toList());
        List<Label> labels = new ArrayList<Label>();
        if (CollectionUtils.isNotEmpty(labelIds)) {
            QueryWrapper<Label> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(Label::getId, labelIds);
             labels = this.list(queryWrapper);
        }
        //判断获取的是否为空如果为空就返回null
        if (CollectionUtils.isNotEmpty(labels)) {
            return labels;
        } else {
            return null;
        }
    }

}